package com.mgg.auth.jwt;

import com.mgg.auth.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @Author: lijun
 * @Date: 2018/9/3 21:34
 */
@Configuration
public class TokenStoreConfig {

	@Autowired
	private RedisConnectionFactory redisConnectionFactory;

	@Bean
	@ConditionalOnProperty(prefix = "mgg.security.oauth2", name = "storeType", havingValue = "redis")
	public TokenStore redisTokenStore() {
	    System.out.print("redisTokenStore");
		return new RedisTokenStore(redisConnectionFactory);
	}
	
	@Configuration
	@ConditionalOnProperty(prefix = "mgg.security.oauth2", name = "storeType", havingValue = "jwt", matchIfMissing = true)
	public static class JwtTokenConfig {

		@Autowired
		private SecurityProperties securityProperties;

		@Autowired
		private RedisConnectionFactory redisConnectionFactory;
		
		@Bean
		public TokenStore jwtTokenStore() {
            System.out.print("jwtTokenStore");
			RedisJwtTokenStore redisJwtTokenStore = new RedisJwtTokenStore(jwtAccessTokenConverter(), redisConnectionFactory);
			return redisJwtTokenStore;
		}
		
		@Bean
		public JwtAccessTokenConverter jwtAccessTokenConverter() {
			JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
			accessTokenConverter.setSigningKey(securityProperties.getOauth2().getJwtSigningKey());
			DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
			accessTokenConverter.setAccessTokenConverter(defaultAccessTokenConverter);
			return accessTokenConverter;
		}
	}
}
